from flask import Flask, request
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

# 创建拓展插件实例
db = SQLAlchemy()
migrate = Migrate(app, db)
# 创建应用程序 app
app = Flask(__name__)
# 配置 SQLite 数据库, 默认存放在 app instance 文件夹下
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/flask_demo'
# 讲拓展插件对象绑定到程序实例
db.init_app(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), unique=True, nullable=False)
    email = db.Column(db.String(32))


with app.app_context():
    db.create_all()


@app.get("/user")
def user_list():
    users = db.session.execute(db.select(User).order_by(User.username)).scalars()
    return {"message": "ok", "data": [user.json() for user in users]}


@app.post("/user")
def create_user():
    data = request.get_json()
    user = User(username=data.get("username"), email=data.get("email"))
    db.session.add(user)
    db.session.commit()
    return {"message": "ok", "data": user.json()}


@app.get("/user/<int:uid>")
def user_detail(uid):
    user = db.get_or_404(User, uid)
    return {"message": "ok", "data": user.json()}


@app.delete("/user/<int:uid>")
def user_delete(uid):
    user = db.get_or_404(User, uid)
    db.session.delete(user)
    db.session.commit()
    return {"message": "ok", "data": user.json()}
